<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\BindHouseRequest;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\LoginWechatRequest;
use App\Http\Requests\PasswordBackRequest;
use App\Http\Requests\RegisterRequest;

use App\Models\ClientUser;
use App\Models\ClientUserHouse;
use App\Models\ClientUserTicket;
use App\Models\House;
use App\Models\HouseDistrict;
use App\Models\HouseDistrictOwner;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends CommonController
{
	
	/**
	 * @param BasicRequest $request
	 * @return array
	 * 用户基本信息
	 */
	public function info(BasicRequest $request){
		$uid = $request->input('id');
		$user = ClientUser::select(['id','username','avatar','mobile','email','realname','signature'])->findOrFail($uid);
		$house_id = ClientUserHouse::where(['uid'=>$uid])->orderBy('primary','desc')->value('house_id');
		$user->house = House::where('house_id','=',$house_id)->value('house_sn');
		return json_success('OK',$user);
	}
	
	/**
	 * @param LoginRequest $request
	 * @return array
	 * 使用账号密码登录
	 */
	public function login(LoginRequest $request){
		$mobile = $request->input('username');
		$password = $request->input('password');
		$clientUser = new ClientUser();
		$uid = $clientUser->checkLogin($mobile,$password,[1,3]);
		wechat_update($uid);
//			$ticket = login(1);
		$data = login($uid);
		return json_success('OK',$data);
	}
	
	/**
	 * @param LoginWechatRequest $request
	 * @return array
	 * 微信登录授权，判断是否绑定了平台手机号，如果绑定直接登录，未绑定就提示绑定
	 */
	public function login_wechat(LoginWechatRequest $request){
		$openid = $request->input('openid');
		$unionid = $request->input('unionid');
		$uid = ClientUser::where(['unionid'=>$unionid])->value('id');
		if($uid){
			$ticket = login($uid);
			return json_success('OK',$ticket);
		}else{
			$data = $request->only(['openid','unionid','name','iconurl','gender']);
			return json_login('授权完成，请绑定平台账号',$data);
		}
	}

    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
	public function register(RegisterRequest $request){
		$username = $request->input('username');
		$mobile = $request->input('mobile');
		$password = $request->input('password');
		$sms_code = $request->input('sms_code');	// 短信验证码
		// 验证短信码
		$code = cache('register_sms_'.$mobile);
		if(strcmp($code,$sms_code) !== 0){
			throw new ApiException('短信验证码错误(可重复输入)');
		}
		$clientUser = new ClientUser();

		$uid = $clientUser->register($username,$mobile,$password);

		wechat_update($uid);
		$data = login($uid);
		return json_return($uid,'','注册成功',$data);
	}
	
	/**
	 * 发送注册短信验证码
	 */
	public function register_sms(Request $request){
		$mobile = $request->input('mobile');
		$cache_key = 'register_sms_'.$mobile;
		\Validator::make($request->all(),[
			'mobile'		=> 'required|size:11',
		],[
			'mobile.required'	=> '请填写11位手机号码',
			'mobile.size'		=> '请填写11位手机号码',
		])->validate();
		if(cache($cache_key.'_action')) {
			throw new ApiException('操作繁忙，请耐心等待');
		}
		
		if(env('APP_ENV') == 'online'){
			$code = create_verify_code(4);
			$timeout = 1;		// 60秒
			$var = send_message($mobile,'验证码',[$code,30]);
		}else{
			$code = '8888';
			$timeout = 0.05;	// 3秒
			$var = true;
		}
		cache([$cache_key=>$code],30);
		cache([$cache_key.'_action'=>$code],$timeout);	// 操作单独缓存
		return json_return($var,'','短信已发送');
	}
	
	/**
	 * @param BindHouseRequest $request
	 * @return array
	 * 获取可用的房屋
	 */
	public function bind_house(BindHouseRequest $request){
		$lat = $request->input('lat');	// 经
		$lng = $request->input('lng');	// 纬

		$data = HouseDistrict::select(DB::raw('*,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))->district()->orderBy('distance','asc')->limit(10)->get();
		return json_success('OK',$data);
	}
	
	// 小区下级信息
	public function bind_house_next(Request $request){
		$parent_id = $request->input('parent_id');
		$data = HouseDistrict::where(['parent_id'=>$parent_id])->orderBy('name','asc')->get();
		return json_success('OK',$data);
	}
	
	/**
	 * @param BasicRequest $request
	 * @throws ApiException
	 * @return array
	 * 根据房屋信息查询到主业主
	 */
	public function bind_house_owner(BasicRequest $request){
		$last_id = $request->input('house_id');
		$owner = HouseDistrictOwner::where(['house_id'=>$last_id])->orderBy('if_primary','desc')->first();
		if(empty($owner)){
			throw new ApiException('该房屋不可绑定');
		}
		$owner->mobile = hidden_mobile($owner->mobile);
          $owner->house_name = ClientUserHouse::firstOrNew(['id'=>$last_id])->getNameLong($last_id);

		return json_success('OK',$owner);
	}
	
	// 绑定小区信息提交
	public function bind_house_submit(Request $request){

		$this->check_login();
		$last_id = $request->input('house_id');
		$sms_code = $request->input('sms_code');
		$house_owner = HouseDistrictOwner::where(['house_id'=>$last_id])->first();
		$code = cache('user_bind_house_sms_'.$house_owner->mobile);
		
		if(strcmp($code,$sms_code) !== 0){
			throw new ApiException('短信验证码错误(可重复输入)');
		}
		$house_children = HouseDistrict::where(['parent_id'=>$last_id])->count();
		if($house_children){
			throw new ApiException('房屋信息未选择完整');
		}
          $parents_id= (new HouseDistrict)->getParentsId($last_id);
		$add = [
			'uid'		=> $this->uid,
			'house_id'	=> $last_id,
               'floor_id'     => $parents_id['0']['id'],
               'village_id'   => $parents_id['1']['id'],
		];
		$var = ClientUserHouse::create($add)->id;
		$house_detail = ClientUserHouse::find($var)->detail();
		return json_return($var,'','恭喜您绑定成功！',$house_detail);
	}

	// 绑定发送短信验证
	public function bind_house_sms(Request $request){
		$this->check_login();
		$last_id = $request->input('house_id');
		if(empty($last_id)){
			throw new ApiException('请传递房屋ID参数');
		}
		$house_owner = HouseDistrictOwner::where(['house_id'=>$last_id])->first();
		if(empty($house_owner)){
			throw new ApiException('该房屋不可绑定');
		}
		$cache_key = 'user_bind_house_sms_'.$house_owner->mobile;
		if(cache($cache_key.'_action')){
			throw new ApiException('操作繁忙，请耐心等待');
		}
		if(env('APP_ENV') == 'online'){
			$code = create_verify_code(4);
			$timeout = 1;		// 60秒
			$var = send_message($house_owner->mobile,'验证码',[$code,30]);
		}else{
			$code = '8888';
			$timeout = 0.05;	// 3秒
			$var = true;
		}
		cache([$cache_key=>$code],30);
		cache([$cache_key.'_action'=>$code],$timeout);	// 操作单独缓存
		return json_return($var,'','短信已发送');
	}
	
	// 退出登录
	public function logout(){
		$var = logout();
		return json_return($var,'','已退出登录');
	}
	
	/**
	 * @param PasswordBackRequest $request
	 * @return array
	 * @throws ApiException
	 * 忘记密码，使用短信码重置密码
	 */
	public function password_reset(PasswordBackRequest $request){
		$mobile = $request->input('mobile');
		$password_new = $request->input('password_new');
		$sms_code = $request->input('sms_code');
		// 验证短信码
		$code = cache('user_password_reset_sms_'.$mobile);
		if(strcmp($code,$sms_code) !== 0){
			throw new ApiException('短信验证码错误(可重复输入)');
		}
		$clientUser = new ClientUser();
		$user = $clientUser->where(['mobile'=>$mobile])->whereIn('type',[1,3])->first();
		if(empty($user)){
			throw new ApiException('找不到该用户');
		}
		$password_gen = $clientUser->passwordEncodeSalt($password_new,$user->salt);
		$var = ClientUser::where(['mobile'=>$mobile])->whereIn('type',[1,3])->update(['password'=>$password_gen]);
		return json_return($var,'','密码重置成功，请使用新密码登录');
	}
	
	/**
	 * @param Request $request
	 * @return array
	 * 发送忘记密码短信码
	 */
	public function password_reset_sms(Request $request){
		$mobile = $request->input('mobile');
		$cache_key = 'user_password_reset_sms_'.$mobile;
		\Validator::make($request->all(),[
			'mobile'		=> 'required|size:11',
		],[
			'mobile.required'	=> '请填写11位手机号码',
			'mobile.size'		=> '请填写11位手机号码',
		])->validate();
		if(cache($cache_key.'_action')){
			throw new ApiException('操作繁忙，请耐心等待');
		}
		if(env('APP_ENV') == 'online'){
			$code = create_verify_code(4);
			$timeout = 1;		// 60秒
			$var = send_message($mobile,'验证码',[$code,30]);
		}else{
			$code = '8888';
			$timeout = 0.05;	// 3秒
			$var = true;
		}
		cache([$cache_key=>$code],30);
		cache([$cache_key.'_action'=>$code],$timeout);	// 操作单独缓存
		return json_return($var,'','短信已发送');
	}
}
